import datetime
import backtrader as bt
import pandas as pd
class Dual_MA(bt.Strategy):
    #策略参数
    def __init__(self):
        self.pfast = 10  # 快周期均线周期
        self.pslow = 30  # 慢周期均线周期

        sma1= bt.ind.SMA(period=self.pfast)
        sma2= bt.ind.SMA(period=self.pslow)  # 移动平均线

        self.crossover=bt.ind.CrossOver(sma1, sma2)
    def next(self):
        if not self.position: # 没有仓位
            if self.crossover[0]>0:
                self.buy()
        else:
            if self.crossover[0]<0:
                self.close()

cerebro = bt.Cerebro()

df = pd.read_csv('Pre_RB_data.csv')
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)
brf_daily=bt.feeds.PandasData(dataname=df,
                              fromdate=datetime.datetime(2020,1,1),
                              todate=datetime.datetime(2025,6,30))

cerebro.adddata(brf_daily)
cerebro.addstrategy(Dual_MA)
cerebro.broker.setcash(30000)
cerebro.broker.setcommission(0.001)
cerebro.run()
cerebro.plot(style='candle')
